Request & RequestInit

The Request class represents a complete configuration of an HTTP request. It can be passed directly to the fetch() method or used to clone, modify, or retry an existing request.

In Scripting, the Request API behaves similarly to the browser’s Fetch API but adds native extensions, including:

  • Binary Data type support for request bodies
  • Custom redirect handling
  • Request timeout and cancellation
  • Optional allowance for insecure (HTTP) requests
  • Debug labels for internal logging

Definition

1class Request {
2  url: string
3  method: string
4  headers: Headers
5  body?: Data | FormData | string | ArrayBuffer
6  allowInsecureRequest?: boolean
7  handleRedirect?: (newRequest: RedirectRequest) => Promise<RedirectRequest | null>
8  shouldAllowRedirect?: (newRequest: Request) => Promise<boolean> // deprecated
9  timeout?: DurationInSeconds
10  signal?: AbortSignal
11  cancelToken?: CancelToken // deprecated
12  debugLabel?: string
13
14  constructor(input: string | Request, init?: RequestInit)
15  clone(): Request
16}

Constructor

new Request(input: string | Request, init?: RequestInit)

Creates a new Request instance from either a URL string or an existing Request object.

Parameters

Parameter Type Description
input string Request
init RequestInit Optional configuration object defining request settings (see below).

Properties

Property Type Description
url string The full URL of the request.
method string The HTTP method (default is "GET").
headers Headers A headers object representing the request headers.
body Data | FormData | string | ArrayBuffer | undefined The request body, used only for non-GET and non-HEAD requests.
allowInsecureRequest boolean Whether to allow plain HTTP requests (default false).
handleRedirect (newRequest: RedirectRequest) => Promise<RedirectRequest | null> Custom redirect handler. Return null to cancel the redirect.
shouldAllowRedirect (newRequest: Request) => Promise<boolean> Deprecated legacy redirect handler.
timeout number Timeout in seconds. The request will automatically abort after this duration.
signal AbortSignal Abort signal from an AbortController, allowing manual cancellation.
cancelToken CancelToken Deprecated. Older cancellation mechanism; prefer signal.
debugLabel string Optional label displayed in logs for debugging and tracking requests.

Methods

clone(): Request

Creates and returns a copy of the current request. The cloned object can be safely modified (e.g., updating headers or timeout) without affecting the original request.

Example

1const req1 = new Request("https://api.example.com/user", {
2  method: "POST",
3  headers: { "Content-Type": "application/json" },
4  body: JSON.stringify({ name: "Alice" }),
5})
6
7const req2 = req1.clone()
8console.log(req2.method) // "POST"

Examples

Example 1 — Creating a Simple Request

1const request = new Request("https://api.example.com/data", {
2  method: "GET",
3  headers: {
4    "Accept": "application/json",
5  },
6  debugLabel: "Fetch User Data",
7})
8
9const response = await fetch(request)
10const result = await response.json()
11console.log(result)

Example 2 — POST Request with a Body

1const request = new Request("https://api.example.com/upload", {
2  method: "POST",
3  headers: { "Content-Type": "application/json" },
4  body: JSON.stringify({ fileId: "abc123" }),
5  timeout: 15,
6})
7
8const response = await fetch(request)
9console.log(await response.text())

Example 3 — Cloning and Modifying a Request

1const base = new Request("https://api.example.com/posts", {
2  method: "POST",
3  headers: { "Content-Type": "application/json" },
4})
5
6const cloned = base.clone()
7cloned.headers.set("Authorization", "Bearer token-123")
8cloned.debugLabel = "Authorized Upload"
9
10await fetch(cloned)

RequestInit Interface

The RequestInit interface defines configuration options for HTTP requests. It is used as the second argument to fetch() or the optional configuration object when creating a new Request. Scripting extends this interface with additional native fields.


Definition

1type RequestInit = {
2  method?: string
3  headers?: HeadersInit
4  body?: Data | FormData | string | ArrayBuffer
5  allowInsecureRequest?: boolean
6  handleRedirect?: (newRequest: RedirectRequest) => Promise<RedirectRequest | null>
7  shouldAllowRedirect?: (newRequest: Request) => Promise<boolean> // deprecated
8  timeout?: DurationInSeconds
9  signal?: AbortSignal
10  cancelToken?: CancelToken // deprecated
11  debugLabel?: string
12}

Field Descriptions

Field Type Description
method string The HTTP method such as "GET", "POST", "PUT", "DELETE". Default: "GET".
headers HeadersInit Request headers, which can be a Headers object, key-value object { key: value }, or array of [key, value] pairs.
body Data | FormData | string | ArrayBuffer The request body. Ignored for GET and HEAD requests.
allowInsecureRequest boolean Allows HTTP requests (insecure). Default: false.
handleRedirect (newRequest: RedirectRequest) => Promise<RedirectRequest | null> Custom redirect handler. Return null to block redirection.
shouldAllowRedirect (newRequest: Request) => Promise<boolean> Deprecated. Older redirect callback.
timeout number Request timeout in seconds. Triggers AbortError if exceeded.
signal AbortSignal Used to abort requests manually through an AbortController.
cancelToken CancelToken Deprecated cancellation mechanism. Use signal instead.
debugLabel string A label displayed in the debug log for identifying requests.

Relationship with fetch()

RequestInit is typically passed as the second parameter to fetch() to configure a network request.

1const response = await fetch("https://example.com/data", {
2  method: "POST",
3  headers: { "Content-Type": "application/json" },
4  body: JSON.stringify({ id: 123 }),
5  timeout: 10,
6  debugLabel: "Upload JSON",
7})

Relationships with Other Classes

Class Description
Headers Manages request headers, used with the headers field.
Data Represents binary data. Can be used as the request body for file uploads or raw bytes.
FormData Builds multipart/form-data bodies for form or file submissions.
AbortController / AbortSignal Enables manual request cancellation.
CancelToken Deprecated cancellation mechanism retained for backward compatibility.
RedirectRequest Represents the redirected request passed to handleRedirect.

Examples

Example 1 — Custom Redirect Handling

1const response = await fetch("https://example.com/start", {
2  handleRedirect: async (newRequest) => {
3    console.log("Redirect detected:", newRequest.url)
4    if (newRequest.url.includes("blocked")) return null
5    return newRequest
6  },
7})

Example 2 — Allowing Insecure Requests

1const response = await fetch("http://insecure.example.com/data", {
2  allowInsecureRequest: true,
3})
4console.log(await response.text())

Example 3 — Using a Debug Label

1await fetch("https://example.com/api/ping", {
2  debugLabel: "Ping Request",
3})
4// The log panel will display the label "Ping Request"

RedirectRequest Interface

When a request encounters an HTTP redirect, and a handleRedirect callback is defined in the Request or RequestInit object, the system will invoke that callback before following the redirect. The callback receives a RedirectRequest object, which describes the full details of the redirect request. You can inspect or modify this object to control whether and how the redirect should proceed.


Interface Definition

1interface RedirectRequest {
2  method: string
3  url: string
4  headers: Record<string, string>
5  cookies: Cookie[]
6  body?: Data
7  timeout?: number
8}

Field Descriptions

Field Type Description
method string The HTTP method for the redirected request (e.g., "GET", "POST").
url string The full target URL of the redirect.
headers Record<string, string> The HTTP headers to be sent with the redirect request. You can modify these before proceeding.
cookies Cookie[] The list of cookies available for the redirected request (same format as Response.cookies).
body Data (optional) The body of the redirect request, if applicable (e.g., for non-GET methods).
timeout number (optional) The request timeout in seconds.

Use Cases

The handleRedirect callback allows you to:

  • Inspect and validate redirect destinations for security or logic reasons.
  • Modify redirect requests (add headers, update method, or include authorization tokens).
  • Block unwanted or unsafe redirects.

When the callback returns:

  • A modified RedirectRequest → The redirect proceeds using your modified configuration.
  • null → The redirect is canceled, and the fetch() call resolves with the current response.

Example: Intercepting and Controlling Redirects

1const response = await fetch("https://example.com/start", {
2  handleRedirect: async (redirect) => {
3    console.log("Redirecting to:", redirect.url)
4
5    // Block redirects to external domains
6    if (!redirect.url.startsWith("https://example.com")) {
7      console.warn("Blocked external redirect:", redirect.url)
8      return null
9    }
10
11    // Add authorization header to redirected request
12    redirect.headers["Authorization"] = "Bearer my-token"
13    return redirect
14  },
15})

Example: Modifying Redirect Method and Body

1const response = await fetch("https://api.example.com/login", {
2  handleRedirect: async (redirect) => {
3    // Keep the request body when redirecting to a confirmation endpoint
4    if (redirect.url.includes("/finalize")) {
5      redirect.method = "POST"
6      redirect.body = Data.fromRawString("action=confirm", "utf-8")
7    }
8    return redirect
9  },
10})

Notes

  • If handleRedirect is not defined, all redirects are automatically followed by default.
  • Returning null from the callback prevents further redirection.
  • Cookies are not automatically forwarded; you can manually inspect and decide whether to reuse cookies from redirect.cookies.
  • Any modifications made to the RedirectRequest (such as headers or method) will be applied before the next request is executed.

Summary

Request and RequestInit form the foundation of Scripting’s networking system:

  • Request encapsulates a complete HTTP request and can be reused or cloned.
  • RequestInit defines configuration options for flexible initialization.
  • Together, they integrate tightly with fetch(), Response, Headers, Data, and FormData.